<template>
  <el-container>
    <el-header>
      <div align="center">
        <h1>Real World博客</h1>
        <h3>大开你的眼界</h3>
      </div>
    </el-header>
    <el-container>
      <el-main>
        <div class="tabs-container">
          <el-tabs v-model="activeTab" @tab-click="handleTabClick">
            <el-tab-pane label="全部文章" name="global">
              <div class="article-list">
                <div
                  class="article-preview"
                  v-for="(article, index) in globalArticles"
                  :key="index"
                >
                  <div>
                    <div class="info">
                      <div><el-avatar :src="avatar" /></div>
                      <div>
                        <router-link to="/profile">
                          {{ article.authorId }}
                        </router-link>
                        <span class="date">{{
                          formatDate(article.createdAt)
                        }}</span>
                      </div>
                    </div>
                    <el-button round size="small" class="pull-xs-right">
                      <i class="el-icon-star-on"></i> 29
                    </el-button>
                  </div>
                  <router-link :to="`/article/${article.slug}`">
                    <h1>{{ article.title }}</h1>
                    <p>
                      {{ article.description }}
                    </p>
                    <p>查看更多...</p>
                  </router-link>
                </div>
                <hr color="EBEDF0" style="margin-left: 10rem" />
              </div>
            </el-tab-pane>
            <el-tab-pane label="我的文章" name="my">
              <div class="article-list">
                <div
                  class="article-preview"
                  v-for="(article, index) in myFeedArticles"
                  :key="index"
                >
                  <div>
                    <div class="info">
                      <div><el-avatar :src="avatar" /></div>
                      <div>
                        <router-link to="/profile">
                          {{ article.authorId }}
                        </router-link>
                        <span class="date">{{
                          formatDate(article.createdAt)
                        }}</span>
                      </div>
                    </div>
                    <el-button round size="small" class="pull-xs-right">
                      <i class="el-icon-star-on"></i> 29
                    </el-button>
                  </div>
                  <router-link :to="`/article/${article.slug}`">
                    <h1>{{ article.title }}</h1>
                    <p>
                      {{ article.description }}
                    </p>
                    <p>查看更多...</p>
                    <!-- 添加编辑按钮 -->
                  </router-link>
                  <el-button
                    type="primary"
                    size="small"
                    @click="editArticle(article)"
                    class="edit-button pull-xs-right"
                    >编辑</el-button
                  >
                </div>
                <hr color="EBEDF0" />
              </div>
            </el-tab-pane>
          </el-tabs>
        </div>
      </el-main>
      <el-aside class="sidebar">
        <p>热门标签</p>
        <el-tag
          v-for="(tag, index) in tags"
          :key="index"
          effect="dark"
          size="medium"
        >
          {{ tag }}
        </el-tag>
      </el-aside>
    </el-container>
  </el-container>

  <!-- 添加模态窗口 -->
  <el-dialog v-model="editModalVisible" title="编辑文章">
    <el-form :model="editingArticle">
      <el-form-item label="标题" prop="title">
        <el-input v-model="editingArticle.title"></el-input>
      </el-form-item>
      <el-form-item label="描述" prop="description">
        <el-input v-model="editingArticle.description"></el-input>
      </el-form-item>
      <el-form-item label="正文" prop="body">
        <el-input v-model="editingArticle.body" type="textarea"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="editModalVisible = false">取消</el-button>
        <el-button type="primary" @click="updateArticle">更新</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, onMounted } from "vue";
import axios from "axios";
import { ElMessage } from "element-plus"; // 导入ElMessage
import { useUserStore } from "../stores/user"; // 817

const userStore = useUserStore(); // 817

const activeTab = ref("global");
const globalArticles = ref([]);
const myFeedArticles = ref([]);
const avatar = ref("https://api.realworld.io/images/demo-avatar.png");
const tags = ref([
  "软件编程",
  "javascript",
  "全栈开发",
  "Vue.js",
  "XD",
  "PhotoShop",
  "node",
  "Springboot",
]);
const userId = ref(localStorage.getItem("user-id"));
const editModalVisible = ref(false);
const editingArticle = ref({});

onMounted(async () => {
  try {
    const globalResponse = await axios.get("/api/articles");
    globalArticles.value = globalResponse.data;
    const myFeedResponse = await axios.get(
      `/api/articles/author/${userId.value}`
    );
    myFeedArticles.value = myFeedResponse.data;
  } catch (err) {
    console.error(err);
  }
});

function handleTabClick(tab) {
  if (tab.name === "my") {
    loadMyFeed();
  } else {
    loadGlobalFeed();
  }
}

async function loadGlobalFeed() {
  try {
    const response = await axios.get("/api/articles");
    globalArticles.value = response.data;
  } catch (err) {
    console.error(err);
  }
}

async function loadMyFeed() {
  try {
    const response = await axios.get(`/api/articles/author/${userId.value}`);
    myFeedArticles.value = response.data;
  } catch (err) {
    console.error(err);
  }
}

// 日期格式化函数
function formatDate(dateString) {
  const date = new Date(dateString);
  return date.toLocaleDateString();
}

function editArticle(article) {
  editingArticle.value = { ...article };
  editModalVisible.value = true;
}

async function updateArticle() {
  try {
    const response = await axios.put(
      `/api/articles/${editingArticle.value.slug}`,
      {
        title: editingArticle.value.title,
        description: editingArticle.value.description,
        body: editingArticle.value.body,
      }
    );

    // 更新文章列表中的文章
    const updatedArticle = response.data;
    myFeedArticles.value = myFeedArticles.value.map((article) =>
      article.slug === updatedArticle.slug ? updatedArticle : article
    );

    // 关闭模态窗口
    editModalVisible.value = false;

    // 提示消息
    ElMessage({
      message: "文章已更新。",
      type: "success",
    });
  } catch (err) {
    console.error(err);
    ElMessage({
      message: "更新文章时发生错误。",
      type: "error",
    });
  }
}
</script>

<style scoped>
/* scoped限制css样式仅限于本组件,以免造成冲突 */

/* 设置el-header样式 */
.el-header {
  background-color: #67c23a; /* 设置背景颜色 */
  color: white; /* 设置文字颜色 */
  height: 150px; /* 设置一个明确的高度，可以根据需要调整 */
  display: flex;
  justify-content: center; /* 水平居中 */
  align-items: center; /* 垂直居中 */
  font-size: 20px; /* 设置字体大小 */
}

/* 为文章预览设置底部边框 */
.article-preview {
  margin-top: 2rem;
  margin-bottom: 3rem;
  padding-bottom: 0.5rem; /* 添加底部内边距以与边框分离 */
}
/* 为.el-tabs设置左边距 */
.tabs-container {
  margin-left: 10rem;
}
/* 为文章描述和其他文字设置灰色 */
.article-preview p,
p {
  color: #909399; /* 文字颜色设置为灰色 */
}

/* 移除所有超链接的下划线 */
a {
  text-decoration: none;
}

/* 设置作者样式 */
.author {
  font-size: 1.2em; /* 增大字体大小 */
  color: #67c23a; /* 设置作者名字的颜色 */
  text-decoration: none; /* 移除下划线 */
}

/* 设置日期样式 */
.date {
  margin-top: 0.5rem;
  display: block;
  color: #909399;
}

/* 减少行距 */
.author,
.date {
  margin: 0; /* 移除默认的外边距 */
  line-height: 1; /* 减小行高 */
}

/* 为头像和作者信息设置并排布局 */
.info {
  display: flex;
  align-items: center;
  margin-left: 0.5rem;
}

/* 为头像设置固定宽度和高度 */
.el-avatar {
  width: 32px;
  height: 32px;
  margin-right: 0.5rem; /* 添加右边距以与作者名字分开 */
}

/* 为文章右侧点赞按钮定义右对齐 */
.pull-xs-right {
  float: right !important;
}

/* 设置文章标题超链样式 */
.preview-link h1 {
  color: black;
}

/* 设置右侧标签栏样式 */
.sidebar {
  flex: 0 0 25%; /* 固定宽度比例 */
  padding-left: 1rem;
}

/* 为每个标签设置背景颜色 */
.sidebar .el-tag {
  background-color: #909399;
  color: white; /* 文字颜色设置为白色以提高可读性 */
  margin-top: 0.25rem;
  margin-right: 0.5rem;
  border: none;
}
</style>